# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import os.path
import re
import urllib.request
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class ScrapyMoviePipeline:
    def open_spider(self, spider):
        self.file = open('movie.json', 'a', encoding='utf-8')

    def process_item(self, item, spider):
        self.file.write(str(item) + '\n')
        return item

    def close_spider(self, spider):
        self.file.close()


class ImgDownloadPipeline:
    def process_item(self, item, spider):
        save_dir = os.path.abspath('img')
        os.makedirs(save_dir, exist_ok=True)

        url = item.get('img')
        name = re.sub(r'[\\/\*?:"<>|]', '-', item.get('name', 'unnamed'))
        img_file_name = os.path.join(save_dir, f"{name}.jpg")

        urllib.request.urlretrieve(url=url, filename=img_file_name)
        return item
